package cn.mania_man.trpg_helper_server.websocket;

import cn.mania_man.trpg_helper_server.room.RequestMessage;
import cn.mania_man.trpg_helper_server.room.Room;
import cn.mania_man.trpg_helper_server.util.UserTagEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;


@Component
@ServerEndpoint("/ws/{roomId}/{userName}/{enterPassword}")
public class User {
    private Session session;
    private String userName;
    private Set<String> role = new HashSet<>();
    private Set<UserTagEnum> tag= new HashSet<>();
    private Room room;

    private Logger logger = LoggerFactory.getLogger(User.class);
    /**
     * websocket使用的方法，请勿调用
     */
    @OnOpen
    public void onOpen(@PathParam("roomId") String roomId, @PathParam("userName") String userName,
                       @PathParam("enterPassword") String password, Session session) {

        //基本数据
        this.setSession(session);
        this.setUserName(userName);
        this.getRole().add("user." + userName);
        Optional<Room> or = Room.getRoomSet().stream().filter(r->r.getName().equals(roomId)).findFirst();
        if(!or.isPresent()){
            close(4001,"未找到房间");
            return;
        }
        Room room = or.get();
        if ( (room.getEnterPassword() == null || room.getEnterPassword().equals(password))) {
            if(room.getUsers().stream().noneMatch(u->u.getUserName().equals(userName))){
                this.setRoom(room);
                this.getRole().add(userName);
                room.join(this);
                logger.info("用户"+userName+"已连接至"+roomId);
            }else {
                close(4001,"用户名已被占用");
            }
        } else {
            close(4001,"未找到房间");
        }
    }

    /**
     * websocket使用的方法，请勿调用
     */
    @OnClose
    public void onClose() {
        if (getRoom() != null) {
            getRoom().exit(this);
        }
    }

    /**
     * websocket使用的方法，请勿调用
     */
    @OnMessage(maxMessageSize = 1024*1024*5)
    public void onMessage(String message, Session session) {
        RequestMessage requestMessage = new RequestMessage(message);
        requestMessage.handle(this);
    }

    /**
     * 服务端主动关闭连接
     */
    public void close(int closeCode,String closeReason){
        try {
            this.session.close(new CloseReason(CloseReason.CloseCodes.getCloseCode(closeCode), closeReason));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public synchronized void sendMessage(String  res){
        this.session.getAsyncRemote().sendText(res);

    }
    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Set<String> getRole() {
        return role;
    }


    public Room getRoom() {
        return room;
    }

    public void setRoom(Room room) {
        this.room = room;
    }

    public Set<UserTagEnum> getTag() {
        return tag;
    }

    public void setRole(Set<String> role) {
        this.role = role;
    }

    public void setTag(Set<UserTagEnum> tag) {
        this.tag = tag;
    }
}
